package org.lifei.auth.interceptors;


import org.lifei.base.annotation.LifPermission;
import org.lifei.base.context.LoginContext;
import org.lifei.org.domain.Employee;
import org.lifei.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeService employeeService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截===================");
        String token = request.getHeader("token");
        System.out.println("token值："+token);
        //根据token获取user
        Employee user = (Employee) LoginContext.loginMap.get(token);
        if (Objects.isNull(user)){
            //没有登录令牌或用户
            response.getWriter().print("{\"msg\":\"NoLogin\",\"success\":false}");
            return false;
        }
        //登录成功
        //鉴定权限
        //判断当前资源是否需要权限
        HandlerMethod method = (HandlerMethod)handler;
        Method method1 = method.getMethod();
        LifPermission annotation = method1.getAnnotation(LifPermission.class);
        if (Objects.isNull(annotation)){
            return true;
        }
        String simpleName = method.getBeanType().getSimpleName();
        //获取资源的权限-sn
        String methodPermission = simpleName+":"+method1.getName();
        //获取用户的权限 用户的id =》 用户角色 =》 用户权限sn list
        List<String> sns = employeeService.selectPermissionSnsById(user.getId());
        //将资源权限和用户权限求交集
        if (!sns.contains(methodPermission)){
            //没有权限
            response.getWriter().print("{\"msg\":\"NoPermission\",\"success\":false}");
            return false;
        }
        return true;
    }
}
